package com.briup.smartcity.web.interceptor;

import com.briup.smartcity.exception.ServiceException;
import com.briup.smartcity.utils.JwtUtil;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Component
public class JwtInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.如果接受到请求 预检请求 解决跨域问题  浏览器发送
        String method = request.getMethod();
        if(method.equals("OPTIONS")){
            //不拦截预检请求
            return true;
        }
        String token = request.getHeader("Authorization");
        //1.token == null
        if(token == null){
            throw new ServiceException("用户未登录");
        }
        //2.验证token
        try {
            JwtUtil.checkSign(token);
        }catch (Exception e){
            e.printStackTrace();//打印token验证失败的原因
            throw new ServiceException("token无效，请重新登录");
        }
        //通过上述验证，通过拦截
        return true;
    }
}
